package com.example.dongbinclient;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

@TargetApi(9)
public class SurveyActivity extends Activity implements Runnable{
	private Button btn_submit = null;
	private Button btn_connect = null;
	private Button btn_close = null;
	private EditText edtInfo1 = null;
	private EditText edtInfo2 = null;
	private EditText edtInfo3 = null;
	
	private String HOST = "192.168.1.241";
	private int PORT = 6000;
	private static final int MSG_RECEIVED = 1;
	private static final int MSG_SEND = 2;
	private static final int MSG_CONNECT = 3;
	private static final String TAG = "DONGBINGSURVEY";

	
	private Socket socket = null;
	private BufferedReader in = null;
	private PrintWriter out = null;
	private String content = "";
	
	private Bundle bundle;
	
	
	Thread mThread;
	DataInputStream ins = null;
	DataOutputStream outs = null;
	
    Handler mHandler = new Handler(){
    	@Override
    	public void handleMessage(Message msg){
        	super.handleMessage(msg);
        	
        	if(msg.what == MSG_CONNECT){
        		Toast.makeText(SurveyActivity.this, "Socket is connected", Toast.LENGTH_SHORT).show();                  

        	} else if(msg.what == MSG_RECEIVED){
        		edtInfo2.setText(edtInfo2.getText().toString() + content);
        	}else if(msg.what == MSG_SEND){

        	} else {
           		Log.v(TAG,"received unknown message");       		
        	}
    	}
    };
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_survey);
        
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().penaltyLog().penaltyDeath().build());
        
        btn_submit = (Button)findViewById(R.id.btnSubmit);
        btn_connect  = (Button)findViewById(R.id.btnSave);
        btn_close = (Button)findViewById(R.id.btnClose);
        
        edtInfo1 = (EditText)findViewById(R.id.editText1);
        edtInfo2 = (EditText)findViewById(R.id.editText2);
        edtInfo3 = (EditText)findViewById(R.id.editText3);
        
        edtInfo1.setText("12345");
        
        btn_submit.setOnClickListener(listener);
        btn_connect.setOnClickListener(listener);
        btn_close.setOnClickListener(listener);
        
        bundle = this.getIntent().getExtras();
        HOST = bundle.getString("ip");
        PORT = Integer.valueOf(bundle.getString("port")).intValue();
        edtInfo1.setText(HOST);
        edtInfo2.setText(String.valueOf(PORT));
        
    }
    
    View.OnClickListener listener = new View.OnClickListener() {
		
		public void onClick(View v) {
			// TODO Auto-generated method stub
			
			switch(v.getId()){
			case R.id.btnSubmit:
			{
				Message msg = new Message();
        		content = edtInfo1.getText().toString();
        		//Toast.makeText(SurveyActivity.this, content, Toast.LENGTH_SHORT).show();
				msg.what = MSG_SEND;
				mHandler.sendMessage(msg); 
				
        		if(socket.isConnected()){
            		//Toast.makeText(SurveyActivity.this, "Socket is connected", Toast.LENGTH_SHORT).show();
        			if(!socket.isOutputShutdown()){
        				out.println(content);
        				/*try{
        				outs.writeUTF(content);
        				} catch(IOException ex){
        				}*/
                		//Toast.makeText(SurveyActivity.this, "out.println(msg)", Toast.LENGTH_SHORT).show();        				
        			}else{
                		Toast.makeText(SurveyActivity.this, "not out.println msg", Toast.LENGTH_SHORT).show();        				
        			}
        		}else{
            		Toast.makeText(SurveyActivity.this, "Socket is connected", Toast.LENGTH_SHORT).show();
        		}      		
				
				break;
				
			}
				
			case R.id.btnSave:
			{
				Message msg = new Message();
        		Toast.makeText(SurveyActivity.this, "connect", Toast.LENGTH_SHORT).show();
				msg.what = MSG_CONNECT;
				mHandler.sendMessage(msg); 
				
		        try{
		        	SocketAddress socAddress = new InetSocketAddress(HOST,PORT);
		        	socket = new Socket();
		        	socket.connect(socAddress, 2000);
		        	
		        	if(socket.isConnected()){
	            		Toast.makeText(SurveyActivity.this, "Socket is connected", Toast.LENGTH_SHORT).show();
//		        		in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		        		out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
		        		
		        	}else{
	            		Toast.makeText(SurveyActivity.this, "Socket is not connected", Toast.LENGTH_SHORT).show();		        		
		        	}
		      		             	
		        	//ins = new DataInputStream(socket.getInputStream());
		        	//outs = new DataOutputStream(socket.getOutputStream());
		        } catch(IOException ex){
		        	//socket.close();
		        	ex.printStackTrace();
		        	ShowDialog("login exception"+ex.getMessage());
		        } 
		        
		        //mThread = new Thread(SurveyActivity.this);
		        //mThread.start();
		        
				break;				
			}
			
			case R.id.btnClose:
			{
	       		if(socket.isConnected()){
            		//Toast.makeText(SurveyActivity.this, "Socket is connected", Toast.LENGTH_SHORT).show();
					try{
						out.close();
						//in.close();
		        		socket.close();       			
			        } catch(IOException ex){
			        	ex.printStackTrace();
			        }
        		}else{
            		Toast.makeText(SurveyActivity.this, "Socket is connected", Toast.LENGTH_SHORT).show();
        		}      						
				break;
			}
			default:
				break;
			}

		}
	};

    private void ShowDialog(String msg) {
		// TODO Auto-generated method stub
    	new AlertDialog.Builder(this).setTitle("notification").setMessage
		(msg).setPositiveButton("OK",new DialogInterface.OnClickListener(){
			public void onClick(DialogInterface dialog,int which){
				
			}
		});
	}
    
    public void run(){

    	try{
    		while(true){
 //            	socket = new Socket(HOST,PORT);
//            	in = new BufferedReader(new InputStreamReader(socket.getInputStream()));    			
    			if(socket.isConnected()){
    				if(!socket.isInputShutdown()){
    					if((content = in.readLine())!=null){
    	            		//Toast.makeText(this, content, Toast.LENGTH_SHORT).show();    						
    						content += "\n";
    						Message msg = new Message();
    						msg.what = MSG_RECEIVED;
    						mHandler.sendMessage(msg);    						
//    						mHandler.sendMessage(mHandler.obtainMessage());
    					}else{
    						
    					}
    				}
    			}

    			
    		}
    	} catch(Exception e){
    		e.printStackTrace();
    	}
    }


	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_survey, menu);
        return true;
    }
	
	@Override
	public void onDestroy(){
		//Toast.makeText(SurveyActivity.this, "Socket is connected", Toast.LENGTH_SHORT).show();
		try{
			out.close();
			//in.close();
    		socket.close();       			
        } catch(IOException ex){
        	ex.printStackTrace();
        }
	}
}
